package com.lottery.game.runner.v2;

import com.alibaba.fastjson.JSON;
import com.lottery.game.common.constants.GameConstants;
import com.lottery.game.core.modules.entity.user.WebsocketMessage;
import com.lottery.game.core.modules.service.app.GameUserService;
import com.lottery.game.core.modules.service.app.WebSocketService;
import com.lottery.game.core.modules.service.app.WebsocketMessageService;
import com.lottery.game.core.modules.service.redis.RedisService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class WebsocketSenderScheduler {

	@Autowired
	private WebsocketMessageService websocketMessageService;

	@Autowired
	private WebSocketService webSocketService;

	@Autowired
	private GameUserService gameUserService;

	@Autowired
	private RedisService redisFeignClient;

	@Value("${server.port}")
	private Integer serverPort;

	/**
	 * 定时任务：定时从表中查询未发送的消息发送
	 */
	//@Scheduled(fixedDelay = 15000, initialDelay = 3000)
	public void send() {
		List<WebsocketMessage> list = websocketMessageService.findUnreceivedMessages();


		for (WebsocketMessage wm : list) {
			Map<String,String> sendMsgMap = new HashMap<>();
			String source = wm.getSenderNickname();
			String sendMsg = wm.getSendMsg();
			String roomNumber = wm.getRoomNumber();
			String chatType = wm.getChatType();

			String currentServerKey = "WSCONNECT_" + serverPort + "_";

			Set<String> wsConnected = redisFeignClient.keys(currentServerKey + "*");

			Set<String> userIds = wsConnected.stream()
					.map(mapper-> mapper.replace(currentServerKey, ""))
					.collect(Collectors.toSet());
			sendMsgMap.put("message_id", wm.getId());
			sendMsgMap.put("sendMsg", wm.getSendMsg());
			if(GameConstants.SENDER_SYSTEM.equals(source)) {

				//满足这个通道的才发
				//if(userIds.contains(wm.getUserId())) {
					 webSocketService.sendToTheUser(JSON.toJSONString(sendMsgMap), wm.getUserId(), chatType,null);
				//}

			} else {
			//	if(userIds.contains(wm.getUserId())) {
					//webSocketService.sendToTheUser(JSON.toJSONString(sendMsgMap), wm.getUserId(),null, roomNumber);
			//	}
			}
		}

	}



}
